const app = getApp();
const AJAX = app.$ajax,
  $wx = app.$wx;

Page({
  data: {
    imgHost: app.imgHost,
    orderType: [
      { title: '待付款', btnText: '支付'},
      { title: '待发货', btnText: '发货'},
      { title: '待收货', btnText: '收货'}
    ],
    noData: false
  },

  onLoad(options){
    let td = this.data;
    if(options.type){
      let type_index = parseInt(options.type);
      wx.setNavigationBarTitle({
        title: td.orderType[type_index].title
      })
      this.setData({
        typeIndex: type_index
      });
      this.getOrderList(); 
    }
  },

  onShareAppMessage(){

  },

  btn(e){
    let ed = e.currentTarget.dataset;

    if(ed.status == 0){
      this.getOrderPay({
        id: ed.id,
        type: 'gzh'
      });
    }else if(ed.status == 2){
      this.finish(ed.id);
    }
  },

  getOrderList(){
    let td = this.data;
    AJAX.orderList({
      loadType: 'bar',
      status: td.typeIndex + 1
    }).then(([status, res, msg]) => {
      if(status){
        this.setData({
          orderList: res,
          noData: res.length === 0 ? true : false
        });
      }else{
        $wx.showToast(msg);
        this.setData({
          noData: true
        });
      }
    });
  },

  finish(id){
    let td = this.data;
    AJAX.finish({
      loadType: 'default',
      loadMsg: '加载中...',
      id
    }).then((status, res, msg) => {
      if(status){
        this.getOrderList();
      }else{
        $wx.showToast(msg);
      }
    });
  },

  getOrderPay(params = {}){
    let _this = this;
    AJAX.orderPay({
      loadType: 'default',
      loadMsg: '支付中...',
      ...params
    }).then(([status, res, msg]) => {
      if(status){
        wx.requestPayment({
          timeStamp: res.timestamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success(res) {
            $wx.showToast('支付成功', {
              success() {
                _this.getOrderList();
              }
            });
          },
          fail(res) {
            $wx.showToast('支付失败');
          }
        });
      }else{
        $wx.showToast(msg);
      }
    });
  }
});